package day05.text04.dao;


import day05.text04.pojo.Goods;
import org.junit.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;


public class Dao {


    //读取数据文件信息
    @Test
    public ArrayList<Goods> read() throws IOException {
        ArrayList<Goods> list = new ArrayList();
        BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream("goods.txt")));


        String s;
        while ((s = bf.readLine()) != null) {
            String[] split = s.split(",");
            list.add(new Goods(split[0], split[1], split[2], split[3]));
        }
        bf.close();
        return list;
    }

    public void writer(ArrayList<Goods> list) throws IOException {

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("goods.txt")));
        for (Goods goods : list) {
            bw.write(goods.getId()+","+goods.getName()+","+goods.getPrice()+","+goods.getWeight());
            bw.newLine();
        }
        bw.close();

    }


    //查看产品信息
    @Test
    public ArrayList<Goods> getGoodsList() throws IOException {

        return  read();

    }
     //添加商品
    public void addGoods(ArrayList<Goods> list) throws IOException {
         writer(list);
    }
      //修改商品
    public void editGoods(int id,Goods goods) throws IOException {
        ArrayList<Goods> list = read();
        list.set(id,goods);
        writer (list);
    }

    public void deleteGoods(int id) throws IOException {
        ArrayList<Goods> list = read();
        list.remove(id);
        writer(list);
    }

}
